package com.decent.ejfadmin.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * describe:获取IP
 *
 * @author 陈豆豆
 * @date 2019/09/07
 */
@SuppressWarnings("StringBufferMayBeStringBuilder")
public final class ToolsExecute {

    /****
     * 获取当前IP
     *
     * @return ip
     */
    public static String getIp() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String ip = request.getHeader("Proxy-Client-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取随即数字
     *
     * @param n 长度
     * @return 随机字符串
     */
    public static String getRandomInt(int n) {
        Random ran = new Random();
        String str = "";
        int fast;
        do {
            fast = ran.nextInt(9);
        } while (fast == 0);
        str += fast;
        for (int i = 1; i < n; i++) {
            str += ran.nextInt(9);
        }
        return str;
    }

    /****
     * 随机卡密 amount 为生产生随机数数量
     *
     * @return 卡密
     */
    @SuppressWarnings("WeakerAccess")
    public static String getRandom(int amount) {
        String pwd = "";
        String[] str = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a",
                "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
                "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
                "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
                "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
                "X", "Y", "Z"};
        for (int i = 0; i < amount; i++) {
            int s = (int) Math.round(Math.random() * (str.length - 1));
            pwd += str[s];
        }
        return pwd;
    }

    /**
     * 签名加密
     *
     * @param keyParams 需要加密的参数
     * @return 密文
     */
    public static String Md5UserKey(List<String> keyParams) {
        StringBuffer md5Str = new StringBuffer(100);
        Collections.sort(keyParams);
        for (String param : keyParams) {
            md5Str.append(param);
        }
        return Md5.getMd5(md5Str.toString(), true, "UTF-8").toUpperCase();
    }

    /**
     * 签名加密（带支付密码或其他签名常量）
     *
     * @param md5List   需要加密的参数
     * @param staticStr 支付密码或其他签名常量
     * @return 密文
     */
    public static String Md5UserKey(List<String> md5List, String staticStr) {
        StringBuffer md5Str = new StringBuffer(100);
        Collections.sort(md5List);
        for (String param : md5List) {
            md5Str.append(param);
        }
        md5Str.append(staticStr);
//        System.out.println(md5Str);
        return Md5.getMd5(md5Str.toString(), true, "UTF-8").toUpperCase();
    }

    /**
     * 组织http请求参数（签名有排序规则）
     *
     * @param map       查询参数
     * @param staticStr 支付密码或其他签名常量
     * @return http参数列表
     */
    public static List<NameValuePair> getHttpParam(Map<String, Object> map, String staticStr) {
        long times = System.currentTimeMillis();
        //组织签名
        List<String> md5List = new ArrayList<>(10);
        md5List.add("times" + times);

        //组织参数
        List<NameValuePair> params = new ArrayList<>(10);
        params.add(new BasicNameValuePair("times", "" + times));

        for (String key : map.keySet()) {
            if (map.get(key) != null && StringUtils.isNotBlank("" + map.get(key))) {
                md5List.add(key + map.get(key));
            }
            params.add(new BasicNameValuePair(key, map.get(key) == null ? "" : StringUtils.trimToEmpty(String.valueOf(map.get(key)))));
        }

        String sign = ToolsExecute.Md5UserKey(md5List, staticStr);
        params.add(new BasicNameValuePair("userkey", sign));

        return params;
    }

    /**
     * 去除小数点后重复的0
     *
     * @param target 数字
     * @return bigDecimal
     */
    @SuppressWarnings("BigDecimalMethodWithoutRoundingCalled")
    public static BigDecimal decimalKillZero(BigDecimal target) {
        if (target != null) {
            target = target.stripTrailingZeros();
            if (target.scale() < 0) {
                target = target.setScale(0);
            }
        }
        return target;
    }
}
